package site.zsxeee.work.bootstrap.backend.controller

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.util.HtmlUtils
import site.zsxeee.work.bootstrap.backend.domain.AppProperties
import site.zsxeee.work.bootstrap.backend.domain.Comment
import site.zsxeee.work.bootstrap.backend.domain.CommentRepository
import site.zsxeee.work.bootstrap.backend.util.ResponseObject
import site.zsxeee.work.bootstrap.backend.util.get
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import kotlin.collections.ArrayList

@Suppress("UNCHECKED_CAST")
@Controller
@RequestMapping("/")
class HomeController {
    @Autowired
    private lateinit var commentRepository: CommentRepository
    @Autowired
    private lateinit var appProperties: AppProperties

    private val limit = 8

    @RequestMapping(method = [RequestMethod.GET], value = ["/"])
    fun staticPage(model: Model, request:HttpServletRequest): String {
        val count = commentRepository.count().toInt()
        val currentPage = (count/limit + (if(count%limit>0) 0 else -1)).takeIf { it>0 }?: 0
        model.addAttribute("commentList", commentRepository.findAll(PageRequest.of(currentPage, limit)).toList().reversed())
        model.addAttribute("currentPage", currentPage)
        val likedList:ArrayList<Int> = ArrayList()
        if(request.cookies != null){
            request.cookies["liked"]?.split("%2C")?.forEach {
                likedList.add(it.toInt())
            }
        }
        model.addAttribute("likedList", likedList)
        return "comment"
    }

    @RequestMapping(method = [RequestMethod.POST], value = ["/"])
    @ResponseBody
    fun ajaxPage(@RequestParam("page") page: Int): List<Comment> {
        if (page<0) return listOf()
        return commentRepository.findAll(PageRequest.of(page, limit)).toList()
    }

    @RequestMapping(method = [RequestMethod.POST], value = ["/submit"])
    @ResponseBody
    fun submitComment(
            @RequestParam("nick-name") nickName: String,
            @RequestParam("comment-content") content: String,
            request: HttpServletRequest
    ): ResponseObject {
        var comment = Comment().also {
            it.id = null
            it.nickName = HtmlUtils.htmlEscape(nickName)
            it.comment = HtmlUtils.htmlEscape(content)
            it.dateTime = Date()
            it.likeNum = 0
        }
        try {
            comment = commentRepository.save(comment)
            val commentsId = request.session.getAttribute("comments_id")
            request.session.setAttribute("comments_id", if (commentsId == null) {
                arrayListOf(comment.id)
            }else{
                (commentsId as ArrayList<Int>).add(comment.id!!)
                commentsId
            })

        } catch (e: Exception) {
            return ResponseObject(false, e.toString())
        }
        return ResponseObject(true, comment.id?.toString())
    }

    @RequestMapping(method = [RequestMethod.POST], value = ["/like"])
    @ResponseBody
    fun submitLike(
            @RequestParam("id") id: Int
    ): ResponseObject {
        val comment = commentRepository.findById(id).get().also {
            it.likeNum = it.likeNum!! + 1
        }
        try {
            commentRepository.save(comment)
        } catch (e: Exception) {
            return ResponseObject(false, e.toString())
        }
        return ResponseObject(true)
    }

    @RequestMapping(method = [RequestMethod.POST], value = ["/del"])
    @ResponseBody
    fun del(
            @RequestParam("") id: Int,
            request: HttpServletRequest,
            response: HttpServletResponse
    ): ResponseObject {
        val comment = commentRepository.findById(id).get()
        if(request.session.getAttribute("is-admin") != true){
            val commentsId = request.session.getAttribute("comments_id") as ArrayList<Int>
            if (!commentsId.contains(comment.id)) {
                return ResponseObject(false, "你没有权限删除该留言！")
            }else{
                commentsId.remove(id)
            }
        }
        try {
            commentRepository.delete(comment)
        } catch (e: Exception) {
            return ResponseObject(false, e.toString())
        }
        return ResponseObject(true)
    }

    @RequestMapping(method = [RequestMethod.POST], value = ["/login"])
    @ResponseBody
    fun login(
            @RequestParam username:String,
            @RequestParam password:String,
            request: HttpServletRequest,
            response: HttpServletResponse
    ): ResponseObject = if(username.trim() == appProperties.username && password == appProperties.password){
        request.session.setAttribute("is-admin", true)
        ResponseObject(true)
    }else{
        ResponseObject(false, "用户名或密码错误！")
    }

    @RequestMapping(method = [RequestMethod.POST], value = ["/logoff"])
    @ResponseBody
    fun logoff(
            request: HttpServletRequest,
            response: HttpServletResponse
    ): ResponseObject {
        request.session.setAttribute("is-admin", false)
        return ResponseObject(true)
    }
}